package com.dstz.sys.util;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

@Component
@SuppressWarnings({"rawtypes", "unchecked"})
public class RedisPubsub extends MessageListenerAdapter {
	public static final String CHANNEL = "pubsub";
	private static Logger LOG = LoggerFactory.getLogger(RedisPubsub.class);
	static RedisTemplate redisTemplate;
	static ConcurrentHashMap<Class, MessageListener> listeners = new ConcurrentHashMap<>();
	
	public RedisPubsub(@Autowired(required=false) RedisTemplate redisTemplate) {
		RedisPubsub.redisTemplate = redisTemplate;
	}

	public void handleMessage(Object msg, String channel) {
		LOG.info("channel: {}, msg: {}", channel, msg);
		MessageListener listener = msg==null ? null : listeners.get(msg.getClass());
		if(listener != null) {
			listener.onMessage(msg);
		}
	}
	
	/** 发布消息对象 */
	public static <T> void pub(T message) {
		if(redisTemplate != null) {
			redisTemplate.convertAndSend(CHANNEL, message);
		}
	}
	
	/** 订阅消息对象 */
	public static <T> void sub(Class<T> clazz, MessageListener<T> listener) {
		listeners.put(clazz, listener);
	}
	
	@FunctionalInterface
	public static interface MessageListener<T> {
		void onMessage(T message);
	}
}
